package com.jy.api.controller;

import com.jy.api.controller.params.NetSchedulingParams;
import com.jy.api.dao.EmployeeDao;
import com.jy.api.dao.NetSchedulingDao;
import com.jy.api.dao.ProductTypeDao;
import com.jy.api.domain.*;
import com.jy.api.service.MemberService;
import com.jy.api.util.TimeToFormateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static java.lang.String.format;

/**
 * Created by hanxi on 2018/4/19.
 */
@Slf4j
@RestController
@RequestMapping(value = "v1/admin/")
public class AdminController {
    private MemberService memberService;
    private JdbcTemplate jdbc;
    @Autowired
    private EmployeeDao employeeDao;
    @Autowired
    private ProductTypeDao productTypeDao;
    @Autowired
    private NetSchedulingDao netSchedulingDao;

    @RequestMapping(method = RequestMethod.GET, value = "/schedul/list")
    public ResponseEntity schedulList(@RequestParam("storeId") String storeId) {
        List<NetScheduling> schedulings = netSchedulingDao.findByStoreId(storeId);
        return ResponseEntity.ok(schedulings);
    }


    @RequestMapping(method = RequestMethod.POST, value = "/schedul/edit")
    public ResponseEntity schedulEdit(@RequestBody NetSchedulingParams params) {
        NetScheduling netScheduling = new NetScheduling();
        if (params.getId() > 0) {
            netScheduling = netSchedulingDao.findOne(params.getId());
        }
        netScheduling.setQty(params.getQty());
        netScheduling.setArea(params.getArea());
        netScheduling.setStoreId(params.getStoreId());
        netScheduling.setNumBegin(params.getNumBegin());
        netSchedulingDao.save(netScheduling);
        return ResponseEntity.ok().build();
    }

    @RequestMapping(method = RequestMethod.POST, value = "/schedul/del")
    public ResponseEntity getDailyMemberStatics(@RequestBody NetSchedulingParams params) {
        netSchedulingDao.delete(params.getId());
        return ResponseEntity.ok().build();
    }


    @GetMapping(path = "employees/{id}/sales-statics")
    public ResponseEntity getEmployeeSalesStatics(@RequestParam(value = "year", required = false) Integer year, @RequestParam(value = "month", required = false) Integer month, @PathVariable String id, @RequestParam("storeId") String storeId, @RequestParam(value = "type") String type, @RequestParam(value = "from", required = false) String from, @RequestParam(value = "to", required = false) String to) {
        Employee employee = employeeDao.findOne(id);
        String username = employee.getUsername();
        BeanPropertyRowMapper itemMapper = new BeanPropertyRowMapper<>(SalesItem.class);
        itemMapper.setPrimitivesDefaultedForNullValue(true);

        List<String> storeIds = new ArrayList<>();
        storeIds.add(storeId);
        storeIds.add("1");//默认不可更改分类
        final List<ProductType> types = productTypeDao.findAllByStoreIdInOrderBySequenceAsc(storeIds);
        HashMap<String, String> typeNames = new HashMap<>();
        types.forEach(productType -> {
            typeNames.put(productType.getId(), productType.getName() + "--" + (null == productType.getParent() ? null : productType.getParent().getId()));
        });

        Sales sales = new Sales();
        List<SalesItem> items;
        if (StringUtils.equals("MONTH", type)) {
            items = jdbc.query("SELECT oi.`product_type_id` as typeId," +
                            "       SUM(oi.`quantity`) AS qty," +
                            "       SUM(oi.`deal_price`) AS amount ,sum(oi.`commission`) as  commission" +
                            "  FROM `order_item` as oi," +
                            "       `order` AS o" +
                            " WHERE o.`creator_id`= ?" +
                            "   and o.`store_id`= ?" +
                            "   and year(o.payment_time) = ?" +
                            "   and month(o.payment_time) = ?" +
                            "   and o.`enabled`= 1" +
                            "   and  o.`status` IN('UNFINISHED', 'FINISHED')" +
                            "   and o.id = oi.`order_id`" +
                            " GROUP BY oi.`product_type_id`"
                    , itemMapper, username, storeId, year, month);
        } else {
            items = jdbc.query("SELECT oi.`product_type_id` as typeId," +
                            "       SUM(oi.`quantity`) AS qty," +
                            "       SUM(oi.`deal_price`) AS amount ,sum(oi.`commission`) as  commission" +
                            "  FROM `order_item` as oi," +
                            "       `order` AS o" +
                            " WHERE o.`creator_id`= ?" +
                            "   and o.`store_id`= ?" +
                            "   and o.payment_time BETWEEN ? and ?" +
                            "   and o.`enabled`= 1" +
                            "   and  o.`status` IN('UNFINISHED', 'FINISHED')" +
                            "   and o.id = oi.`order_id`" +
                            " GROUP BY oi.`product_type_id`"
                    , itemMapper, username, storeId, from, to);
        }
        if (!items.isEmpty()) {
            items.forEach(salesItem -> {
                String tyName = typeNames.getOrDefault(salesItem.getTypeId(), "会员充值");
                if (tyName.equals("会员充值")) {
                    salesItem.setTypeName(tyName);
                } else {
                    salesItem.setTypeName(tyName.split("--")[0]);
                    if (!StringUtils.isBlank(typeNames.get(salesItem.getTypeId()).split("--")[1])) {
                        salesItem.setParentTypeId(typeNames.get(salesItem.getTypeId()).split("--")[1]);
                        ProductType productType = productTypeDao.findOne(salesItem.getParentTypeId());
                        if (productType != null) {
                            salesItem.setParentTypeName(productType.getName());
                        }
                    }
                }
            });
        }

        sales.setItems(items);
        return ResponseEntity.ok(sales);
    }


    @Autowired
    public void setMemberService(MemberService memberService) {
        this.memberService = memberService;
    }

    @Autowired
    public void setJdbc(JdbcTemplate jdbc) {
        this.jdbc = jdbc;
    }
}
